import {Fab, TextField} from "@mui/material";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogActions from "@mui/material/DialogActions";
import Button from "@mui/material/Button";
import {createTheme, ThemeProvider} from "@mui/material/styles";
import React, {useEffect} from "react";
import Cookie from "react-cookies";
import {getQPlayStatus, setQCookies} from "../../utils/request/qrequest";
import ls from "localStorage";
import './LoginQQ.css';

const theme = createTheme({
    palette: {
        primary: {
            main: 'rgba(255,255,255,0)',
            contrastText: 'rgba(255,255,255,0)',
            light: 'rgba(255,255,255,0)'
        },
    },
});

export default function LoginQQ(props){
    const [open, setOpen] = React.useState(false);
    const [text, setText] = React.useState('请输入从QQ音乐官网获取的cookie');
    const [isLogin, setIsLogin] = React.useState(false);
    const [user, setUser] = React.useState("");

    const loadLocalStorage = () => {
        let parse = ls.getItem('qqcookies');
        return parse
    }


    let cookies = Cookie.load('uid');
    const handleClickOpen = () => {
        if(user !== "") {
            setText('请输入从QQ音乐官网获取的cookie\n现有账号: ' + user)
        }
        else
        setText('请输入从QQ音乐官网获取的cookie')
        setOpen(true);

    };
    const saveCookie = (c) =>{

        c = c.replaceAll(' ','')
        c = c.replaceAll('\n','')
        let strings = c.split(';');

        if(c.indexOf("uid") !== -1 && c.indexOf("qqmusic_key") !== -1){
            //console.log('sava COOKIE@@@@@@@@@@@@@@@@@@')
            strings.forEach(element => {
                let is = element.split('=');
                Cookie.save(is[0],is[1]);
            });
        }
    }
    const getUin = () => {
        let result = undefined;

        let c = loadLocalStorage();
        if(!c){
            return result;
        }
        c = c.replaceAll(' ','')
        c = c.replaceAll('\n','')
        let strings = c.split(';');
        if(c.indexOf("uid") !== -1 && c.indexOf("qqmusic_key") !== -1){
            //console.log('sava COOKIE@@@@@@@@@@@@@@@@@@')
            strings.forEach(element => {
                let is = element.split('=');
                if(is[0] === 'uin'){
                    result = is[1];
                }
            });
        }
        return result;
    }
    useEffect(() => {
        let id = Cookie.load('uin');
        if(!id || id === ''){
            id = getUin();
            if(id && id.length > 4)
                saveCookie(loadLocalStorage());
        }
        //console.log(id)
        if (id && id.length > 4) {
            getQPlayStatus(id).then((r) => {
               //console.log(r)
                let userName = r.data.data?.creator?.nick;
                if (userName !== undefined) {
                    setUser(userName);
                    setIsLogin(true);
                }
            })

        } else {
            let s = loadLocalStorage();
            if (s) {
                saveCookie(s);
                let id = Cookie.load('uin');
                //console.log(id)
                if (id) {
                    getQPlayStatus(id).then((r) => {
                        let userName = r.data.data?.creator?.nick;
                        if (userName !== undefined) {
                            setUser(userName);
                            setIsLogin(true);
                        }
                    })
                }
            }
        }
    },[])
    const handleClose = () => {

        setOpen(false);
    };

    const handleOk = () => {
        setText('正在存储Cookies')
        setQCookies(inputvalue,(r) => {
            //console.log(r)

        })
        setTimeout(() => {
            setOpen(false);
            saveCookie(inputvalue);
            setIsLogin(true)
            saveLocalStorage(inputvalue);
        }, 2000);
    };
    var inputvalue = "";
    const changeInput = (event) => {

        inputvalue = event.target.value;

    };
    const saveLocalStorage = (c) => {

        ls.setItem('qqcookies',c)
    }


    return(
        <>
            <div>
                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle>登录QQ</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            {text}
                        </DialogContentText>
                        <TextField
                            autoFocus
                            margin="dense"
                            id="cookie"
                            label={cookies?'已存在账号:' + cookies:'Enter Cookies'}
                            type="email"
                            fullWidth
                            variant="standard"
                            onChange={changeInput}

                        />
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose}>取消</Button>
                        <Button onClick={handleOk}>确认</Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div className="content_q">
                <ThemeProvider theme={theme}>
                    <Fab color="primary" ariant="extended" className='fabqq' onClick={handleClickOpen}>
                        <img  width='64px'  height='64px' src={isLogin?'./icoqq.png' : './unicoqq.png'}/>
                    </Fab>
                </ThemeProvider>
            </div>
        </>
    )

}
